<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { ElInputNumber } from 'element-plus';
import { useForm, useFormRules } from '@/hooks/common/form';
import { $t } from '@/locales';
import {
  deptLevelCodeOptions
  // deptLevelCodeRecord,
  // enableStatusOptions,
  // userGenderOptions
} from '@/constants/business';

defineOptions({ name: 'UserOperateDrawer' });

interface Props {
  /** the type of operation */
  operateType: UI.TableOperateType;
  /** the edit row data */
  rowData?: Api.SystemManage.User | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useForm();
const { defaultRequiredRule } = useFormRules();

const title = computed(() => {
  const titles: Record<UI.TableOperateType, string> = {
    add: $t('page.manage.dept.addDept'),
    edit: $t('page.manage.dept.editDept')
  };
  return titles[props.operateType];
});

type Model = Pick<Api.SystemManage.Dept, 'name' | 'levelCode' | 'sortNum' | 'director'>;

const model = ref(createDefaultModel());

function createDefaultModel(): Model {
  return {
    name: '',
    levelCode: 'dept',
    sortNum: 0,
    director: undefined
  };
}

type RuleKey = Extract<keyof Model, 'name'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  name: defaultRequiredRule
  // status: defaultRequiredRule
};

/** the enabled role options */
// const roleOptions = ref<CommonType.Option<string>[]>([]);

async function getRoleOptions() {
  // const { error, data } = await fetchGetAllRoles();
  // if (!error) {
  //   const options = data.map(item => ({
  //     label: item.roleName,
  //     value: item.roleCode
  //   }));
  //   // the mock data does not have the roleCode, so fill it
  //   // if the real request, remove the following code
  //   const userRoleOptions = model.value.userRoles.map(item => ({
  //     label: item,
  //     value: item
  //   }));
  //   // end
  //   roleOptions.value = [...userRoleOptions, ...options];
  // }
}

function handleInitModel() {
  model.value = createDefaultModel();

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model.value, props.rowData);
  }
}

function closeDrawer() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();
  // request
  window.$message?.success($t('common.updateSuccess'));
  closeDrawer();
  emit('submitted');
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
    getRoleOptions();
  }
});
</script>

<template>
  <ElDrawer v-model="visible" :title="title" :size="500">
    <ElForm ref="formRef" :model="model" :rules="rules" label-position="top">
      <ElFormItem :label="$t('page.manage.dept.name')" prop="name">
        <ElInput v-model="model.name" :placeholder="$t('page.manage.dept.form.name')" />
      </ElFormItem>
      <ElFormItem :label="$t('page.manage.dept.levelCodeTitle')" prop="levelCode">
        <ElRadioGroup v-model="model.levelCode">
          <ElRadio v-for="item in deptLevelCodeOptions" :key="item.value" :value="item.value" :label="$t(item.label)" />
        </ElRadioGroup>
      </ElFormItem>
      <ElFormItem :label="$t('page.manage.dept.directorName')" prop="nickName">
        <ElInput v-model="model.director" :placeholder="$t('page.manage.dept.form.directorName')" />
      </ElFormItem>
      <ElFormItem :label="$t('page.manage.dept.sortNum')" prop="sortNum">
        <ElInputNumber v-model="model.sortNum" :placeholder="$t('page.manage.user.form.userPhone')" />
      </ElFormItem>
    </ElForm>
    <template #footer>
      <ElSpace :size="16">
        <ElButton @click="closeDrawer">{{ $t('common.cancel') }}</ElButton>
        <ElButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</ElButton>
      </ElSpace>
    </template>
  </ElDrawer>
</template>

<style scoped></style>
